﻿<template>
  <div>
    <el-upload ref = 'upload' :action = 'actionUrl' :limit = 'limit' :auto-upload = "true" :file-list = 'fileList' drag
    :on-exceed = 'onExceed' :before-remove = 'removeUpload' :on-preview = "handlePictureCardPreview" :class = "widget.options.disabled ? 'hiddenUploadInput' : ''"
    :http-request = "submitUpload" :disabled = 'showProgress'>
      <i class = "el-icon-upload" v-if = "!showProgress"></i>
      <div class = "el-upload__text" v-if = "!showProgress">将文件拖到此处，或<em>点击上传</em></div>
      <el-progress v-if = "showProgress" type = "circle" :percentage = "currentPercentage"
      :width = '120' style = 'margin-top:10px' :format = 'progressFormat'></el-progress>
    </el-upload>
    <span v-if = "widget.type === 'File' && widget.options.disabled && !dataModel">暂无文件</span>
    <span v-if = "widget.type !== 'File' && widget.options.disabled && (dataModel && !dataModel.length)">暂无文件</span>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  props: ['dataModel', 'widget', 'changeModels', 'showEditElementDataDialog'],
  data () {
    return {
      actionUrl: `${$URL.IMG_UPLOAD_URL}`,
      fileList: [],
      fileReader: '',
      myDataModel: this.dataModel || null,
      limit: null,
      // 上传进度展示
      showProgress: false,
      currentPercentage: 0
    }
  },
  mounted () {
    if (!window.FileReader) {
      this.$message({
        message: '您的浏览器不支持 FileReader API',
        type: 'warning'
      })
    } else {
      this.fileReader = new FileReader()
    }
    this.initPage()
  },
  methods: {
    // 初始化页面时
    initPage () {
      if (this.widget.type === 'File') {
        this.limit = 1
      } else if (this.widget.type === 'Files') {
        this.limit = null
      } else {
        this.limit = this.widget.options.limit
      }
      this.fileList = []
      // 当个文件上传时，为字符串类型
      if (this.widget.type === 'File') {
        this.myDataModel = this.dataModel ? this.dataModel : ''
        if (this.dataModel) {
          let obj = {
            name: this.dataModel,
            url: this.dataModel
          }
          if (this.dataModel.indexOf('/name/') !== -1) {
            obj.name = this.dataModel.slice(this.dataModel.indexOf('/name/') + 6)
          }
          this.fileList.push(obj)
        }
      } else {
        this.myDataModel = (this.dataModel && this.dataModel.length) ? this.dataModel : []
        if (this.dataModel && this.dataModel.length) {
          this.dataModel.forEach(item => {
            if (item) {
              let obj = {
                name: item,
                url: item
              }
              if (item.indexOf('/name/') !== -1) {
                obj.name = item.slice(item.indexOf('/name/') + 6)
              }
              this.fileList.push(obj)
            }
          })
        }
      }
    },
    // 点击下载的方法
    handlePictureCardPreview (file) {
      this.$confirm('确定要下载该文件么', '提示', {
        showClose: false,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.$store.dispatch('changeLoadingText', '文件下载中...')
        this.$store.dispatch('changRouteLoading', true)
        this.getFileBasicInfo(file.url, 'download')
      }).catch(() => {})
    },
    // 文件超过最大上传个数时
    onExceed () {
      this.$message({
        message: '最多只能上传' + this.limit + '个文件',
        type: 'warning'
      })
    },
    // 上传文件移除
    removeUpload (file) {
      if (!this.widget.options.disabled) {
        this.$confirm('确定要移除该文件么,请谨慎操作！', '提示', {
          showClose: false,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonClass: 'el-button--info',
          cancelButtonText: '取消'
        }).then(() => {
          this.$store.dispatch('changeLoadingText', '文件移除中...')
          this.$store.dispatch('changRouteLoading', true)
          // 删除文件的方法
          let downUrl = ''
          if (file.url.indexOf('/name/') !== -1) {
            downUrl = file.url.slice(0, file.url.indexOf('/name/'))
          } else {
            downUrl = file.url
          }
          if (downUrl) {
            if (downUrl.indexOf('/fileset/dl/') !== -1) {
              downUrl = downUrl.replace('/fileset/dl/', '/fileset/recycle/')
            } else {
              downUrl = downUrl.replace('/fileset/', '/fileset/recycle/')
            }
          }
          axios({
            url: downUrl,
            method: 'patch'
          }).then(data => {
            if (data.data.result.code === 'success') {
              // 当个文件时
              if (this.widget.type === 'File') {
                this.myDataModel = ''
              } else {
                // 多个文件时
                if (this.myDataModel && this.myDataModel.length) {
                  this.myDataModel.forEach((item, index) => {
                    if (item === file.url) {
                      this.myDataModel.splice(index, 1)
                    }
                  })
                }
              }
              if (this.fileList.length) {
                this.fileList.forEach((item, index) => {
                  if (item.url === file.url) {
                    this.fileList.splice(index, 1)
                  }
                })
              }
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            } else {
              this.$message({
                message: data.data.result.msg,
                type: 'error',
                duration: 5000
              })
            }
            this.$store.dispatch('changeLoadingText', '数据加载中...')
            this.$store.dispatch('changRouteLoading', false)
          }).catch(error => {
            this.$store.dispatch('changeLoadingText', '数据加载中...')
            this.$store.dispatch('changRouteLoading', false)
            console.log(error)
          })
        }).catch(() => {
        })
        return false
      } else {
        return false
      }
    },
    submitUpload (options) {
      let file = options.file
      let filename = file.name
      if (file) {
        // 进度条相关的控件
        this.showProgress = true
        this.currentPercentage = 0
        this.fileReader.readAsDataURL(file)
        let formData = new FormData()
        formData.append('file', file)
        axios({
          url: $URL.IMG_UPLOAD_URL + '/fileset/upload_stream',
          method: 'post',
          headers: {
            'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
          },
          data: formData,
          onUploadProgress: ProgressEvent => {
            if (ProgressEvent.lengthComputable) {
              let currentPer = parseInt(ProgressEvent.loaded / ProgressEvent.total * 10000) / 100
              this.currentPercentage = currentPer > 100 ? 100 : currentPer
            }
          }
        }).then(data => {
          let dataResult = data.data.result
          if (dataResult.code === 'success') {
            this.currentPercentage = 100
            this.$message({
              message: '上传成功',
              type: 'success'
            })
            this.showProgress = false
            let obj = {
              name: filename,
              url: dataResult.link_url + '/name/' + filename
            }
            this.fileList.push(obj)
            // 单个文件为字符串，多个文件为数组
            if (this.widget.type === 'File') {
              this.myDataModel = dataResult.link_url + '/name/' + filename
            } else {
              this.myDataModel.push(dataResult.link_url + '/name/' + filename)
            }
          } else {
            // 上传失败的提示
            this.uploadFailedMsg()
          }
        }).catch(error => {
          // 上传失败的提示
          this.uploadFailedMsg()
          console.log(error)
        })
      }
    },
    // 进度条的文字格式化
    progressFormat (percentage) {
      return percentage === 100 ? '处理中...' : `${percentage}%`
    },
    // 上传失败的提示
    uploadFailedMsg () {
      // 先清空上传列表中的内容
      this.fileList = []
      this.$refs.upload.clearFiles()
      // 将以成功上传的文件展示在上传列表中--不是单个文件时
      if (this.widget.type !== 'File') {
        if (this.dataModel && this.dataModel.length) {
          this.dataModel.forEach(item => {
            if (item) {
              let obj = {
                name: item.indexOf('/name/') !== -1 ? item.slice(item.indexOf('/name/') + 6) : item,
                url: item
              }
              this.fileList.push(obj)
            }
          })
        }
      }
      this.$message({
        message: '上传失败',
        type: 'error',
        duration: 3000
      })
      this.showProgress = false
    },
    // 根据url获取到文件的基本信息
    getFileBasicInfo (fileUrl, download) {
      let downUrl = ''
      if (fileUrl) {
        let fileName = '文件'
        if (fileUrl.indexOf('/name/') !== -1) {
          downUrl = fileUrl.slice(0, fileUrl.indexOf('/name/'))
          fileName = fileUrl.slice(fileUrl.indexOf('/name/') + 6)
        } else {
          downUrl = fileUrl
        }
        if (downUrl.indexOf('/fileset/dl/') !== -1) {
          downUrl = downUrl.replace('/fileset/dl/', '/fileset/')
        }
        axios({
          url: downUrl,
          method: 'get',
          responseType: 'arraybuffer' // 文件是二进制时
        }).then(data => {
          if (data && data.status === 200 && data.data) {
            let fileType = data.headers['content-type']
            let blobContent = new Blob([data.data], {type: fileType})
            this.downloadblob(blobContent, fileName)
            this.$message({
              message: '下载成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '下载出错',
              type: 'error'
            })
          }
          this.$store.dispatch('changeLoadingText', '数据加载中...')
          this.$store.dispatch('changRouteLoading', false)
        }).catch(error => {
          this.$store.dispatch('changeLoadingText', '数据加载中...')
          this.$store.dispatch('changRouteLoading', false)
          console.log(error)
        })
      } else {
        this.$message({
          message: '没有获取到本文件的下载地址',
          type: 'warning'
        })
      }
    },
    // 下载文件到本地
    downloadblob (blobcontent, filename) {
      if ('msSaveOrOpenBlob' in navigator) {
        // Microsoft Edge and Microsoft Internet Explorer 10-11
        window.navigator.msSaveOrOpenBlob(blobcontent, filename)
      } else {
        // 创建隐藏的可下载链接
        var eleLink = document.createElement('a')
        eleLink.download = filename
        eleLink.style.display = 'none'
        // 字符内容转变成blob地址
        eleLink.href = URL.createObjectURL(blobcontent)
        // 触发点击
        document.body.appendChild(eleLink)
        eleLink.click()
        // 然后移除
        document.body.removeChild(eleLink)
      }
    }
  },
  watch: {
    myDataModel: {
      deep: true,
      handler (val) {
        this.$emit('update:dataModel', val)
      }
    },
    showEditElementDataDialog: {
      deep: true,
      handler (val) {
        if (val) {
          this.initPage()
        }
      }
    }
  }
}
</script>
